/*
 * @Description: 路由权限控制
 * @Author: Liu Zhiwang
 * @Date: 2021-03-27 14:34:23
 * @LastEditTime: 2021-04-13 16:08:34
 * @LastEditors: Liu Zhiwang
 */
import { constantRoutes } from '@/router'
import { isExternal } from '@/utils/validate'

function recursiveRoutes(routes, haveChildren) {
  for (const route of routes) {
    route.component = resolve => require([`@/views${route.menuFilePath}`], resolve)
    // 第一层菜单的外部链接
    if (route.path.startsWith('/') && isExternal(route.path.slice(1))) route.path = route.path.slice(1)

    if (route.children && route.children.length > 0) {
      recursiveRoutes(route.children, 1)
    } else if (route.children.length === 0 && !haveChildren) {
      // 只有一层菜单，且需要在左边栏显示处理
      route.children = [{
        path: '',
        component: resolve => require([`@/views${route.menuFilePath}`], resolve),
        name: route.name,
        meta: route.meta
      }]
      route.alwaysShow = false
      route.component = resolve => require(['@/views/layout'], resolve)
      delete route.name
      delete route.meta
    }
  }
  return routes
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, routes) {
    return new Promise(resolve => {
      const data = recursiveRoutes(routes)
      data.push({ path: '*', redirect: '/404', hidden: true })

      commit('SET_ROUTES', data)
      resolve(data)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
